/** @jsxImportSource @emotion/react */
import {  css } from "@emotion/react";
import * as React from "react";
import {
    Toolbar,
    Navbar,
    useTheme,
    IconButton,
    Button,
    Tabs,
    Tab,
    Layer,
    TabPanel,
    MenuList,
    MenuItem,
    Tooltip,
    IconChevronDown,
    IconPlus,
    DarkMode,
    LightMode,
    Pager,
    IconArchive,
    IconArrowRight,
    ButtonRefComp,
    DarkRefMode,
    TwoHalfRightPanel,
    IconCloud,
    IconArrowLeft,
    IconPackage, Touchable,
} from "customize-easy-ui-component";

import { Link as RouterLink } from "../routing/Link";
import { useMedia } from "use-media";
import  Layout  from "./Layout";
import { InternalItemHandResult, ReportViewProps } from "./comp/base";
import {useContext} from "react";
import {UserContext} from "../routing/UserContext";
import {PreloadedQuery, usePreloadedQuery} from "react-relay/hooks";
import {EachUnitMainQuery} from "../unit/__generated__/EachUnitMainQuery.graphql";
import {ReportStarter} from "./ReportStarter";
//import {OriginalRecordMainQuery} from "./__generated__/OriginalRecordMainQuery.graphql";
import {EditStorageContext} from "./StorageContext";
import useLogoutMutation from "../common/useLogoutMutation";
import RecordStarter from "./RecordStarter";
import {OriginalRecordMainQuery} from "./OriginalRecordMain";
import {DeviceDetail} from "../device/DeviceDetail";

const graphql = require("babel-plugin-relay/macro");

//模板的版本号和相应代码维护管理是个问题；不是下载离线的，而是时刻web在线的文档格式；配套数据库数据加上配套模板才能拼凑出正式文档。要保留维护几年？有人还在用旧的。
//模板类型：支持主报告类型1个+分报告类型多个的情况，报告展示入口管理。模板版本号由后端管理。

interface RecordEditorMainProps {
    prepared: {
        template: any;   //该类型的模板 主入口：
        query: PreloadedQuery<typeof OriginalRecordMainQuery>;
    }
    routeData: any;
    children: React.ReactNode;
}
//首次render时刻template应该还没有获取到的，需要第二次render才能获得到template。
//RecordEditorOrPrint应该直接合体：
function RecordEditorMain( {
           prepared:{
               template: LibofLoadable, query: myQuery
           },
           routeData,
           children
 }:  RecordEditorMainProps
) {
    const theme = useTheme();
    const data = usePreloadedQuery<typeof OriginalRecordMainQuery>(
        OriginalRecordMainQuery,
        myQuery,
    );
    const { getReport: items }=data;

    /*
    旧版本加上EditStorageContext 右边组件编辑立刻能反馈给 左边组件=报告项目、列表的内容。
    跨越两个级别的路由Main组件页面，Context.Provider只能在共同最高一层组件上配上。
    这里和OriginalRecordMain都搞<EditStorageContext.Provider value={{ storage, setStorage }}居然能够互通，本来storage实例都是不一样的，不应该啊可能互通的。
    【揭秘】这里组件保存后，直接修改了Relay的客户端上缓存，对象缓存可就是整个APP共同的；所以右半边路由页面改了保存了后在左边路由组件不用Context也是可能互通=很快就能显示变化跟随数据的。
    虽然两个上下级路由页面，右边页面Relay变更后返回report的data数据，左边页面因为Relay针对同一个report的data就能立刻更新页面。不用EditStorageContext.Provider可以的！
    * */
    return (
      <LibofLoadable fallback={<h4>获取模板主入口</h4>} >
        {
            ( { reportTemplate, originalTemplate} :any) => {
                const originalNode= originalTemplate[routeData.params.verId];
                const reportNode= reportTemplate[routeData.params.verId];
                if(!reportNode || !originalNode)
                     throw new Error(`没有${routeData.params.template}类型${routeData.params.verId}版本${reportNode? '原始记录':'报告'}模板`);
                return (
                 <RecordEditorMainInner items={items}
                                          originalNode={originalNode}
                                          reportNode={reportNode}
                                          routeData={routeData} >
                    {children}
                </RecordEditorMainInner>
                );
            }
        }
      </LibofLoadable>
  );
}

//看 外套
function RecordEditorMainInner( {items, reportNode,originalNode, routeData,children}
        :{items:any, reportNode:any,originalNode:any, routeData:any,children: React.ReactNode}
) {
    const {storage, setStorage} =React.useContext(EditStorageContext);

    React.useEffect(() => {
        const  dat =items&&items.data&&JSON.parse(items.data);
        const  snap =items&&items.snapshot&&JSON.parse(items.snapshot);
        if(snap)   dat && setStorage({...dat, ...snap});
        else  dat && setStorage(dat);
        console.log("参数datdat第三层路由&print qs dat=",dat,"snap",snap);
    }, [items, setStorage]);
    console.log("外套RecordEditorMainInner&2items=",items,"storage跨路由后=",storage);

    return (
       <React.Fragment>
       {
        storage && <RecordStarter  routeData={routeData}  ispId={items?.isp.id}
                             prepared={ {source: storage, template: originalNode} } >
                    {children}
                </RecordStarter>
       }
       { !storage &&
           <div  css={[
                    {
                        display: 'flex',
                        alignItems:'center',
                        justifyContent:'center',
                        height: '100vh',
                    },
                ]}
           >
               <RouterLink href={`/inspect/${items?.isp.id}/report/${items?.id}`}>
                 该报告的基础信息未赋值<hr/>还是返回报告摘要
               </RouterLink>
           </div>
       }
       </React.Fragment>
    );
}


export default RecordEditorMain;
